﻿namespace Fotofly.PhotoViewer
{
    using System;
    using System.Collections.Generic;
    using System.Collections.Specialized;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Animation;
    using System.Windows.Shapes;

    public static class SilverlightUtils
    {
        public static string ServerAddress
        {
            get
            {
                string fullAddres = System.Windows.Application.Current.Host.Source.AbsoluteUri;
                string pageName = System.Windows.Application.Current.Host.Source.AbsolutePath;

                return fullAddres.Replace(pageName, string.Empty);
            }
        }

        public static Uri GenerateLocalUri(string pageName)
        {
            if (pageName.StartsWith("http"))
            {
                return new Uri(pageName);
            }
            else
            {
                return new Uri(SilverlightUtils.ServerAddress.TrimStart('/') + "/" + pageName.TrimStart('/'));
            }
        }

        public static void ReadInitParameters(StartupEventArgs e, ResourceDictionary resourceDictionary)
        {
            if (e.InitParams != null)
            {
                foreach (var item in e.InitParams)
                {
                    resourceDictionary.Add(item.Key.ToLower(), item.Value);
                }
            }
        }

        public static T ReadResource<T>(string parameterName)
        {
            return SilverlightUtils.ReadResource<T>(parameterName, false);
        }

        public static T ReadResource<T>(string parameterName, bool mandatory)
        {
            string resourceName = parameterName.ToString().ToLower();

            if (Application.Current.Resources.Contains(resourceName))
            {
                object unknownObject = Application.Current.Resources[resourceName];

                try
                {
                    return (T)Convert.ChangeType(unknownObject, typeof(T), null);
                }
                catch
                {
                }
            }

            if (mandatory)
            {
                throw new Exception("InitParam was not found: " + parameterName.ToString());
            }
            else
            {
                return default(T);
            }
        }
    }
}
